<template lang="pug">
.star(:class="starType")
  span(v-for="(itemClass,index) in itemClasses" :key="index" :class="itemClass" class="star-item")
</template>

<script type="text/ecmascript-6">
  const LENGTH = 5;
  // 高亮星星
  const CLS_ON = 'on';
  // 半颗星星
  const CLS_HALF = 'half';
  // 灰色星星
  const CLS_OFF = 'off';
  
  export default {
    props: {
      // 图片尺寸:24、36、48
      size: {
        type: Number
      },
      // 星数，最多5颗，可为小数
      score: {
        type: Number
      }
    },
    computed: {
      starType () {
        return 'star-' + this.size;
      },
      // 计算星星样式数组
      // 例如：
      // 输入score:3.6
      // 输出itemClass:['on','on','on','half','off']
      itemClasses () {
        let result = [];
        let score = Math.floor(this.score * 2) / 2;
        let hasDecimal = score % 1 !== 0;
        let intCount = Math.floor(score);
        for (let i = 0; i < intCount; i++) {
          result.push(CLS_ON);
        }
        if (hasDecimal) {
          result.push(CLS_HALF);
        }
        while (result.length < LENGTH) {
          result.push(CLS_OFF);
        }
        return result;
      }
    }
  };
</script>

<style lang="stylus" scoped>
@import "../../static/common/stylus/mixin";
.star
  display:flex
  justify-content:flex-start
  &.star-24
    .star-item
      width:10px
      height:10px
      background-size:10px 10px
      margin-right:3px
      &:last-child
        margin-right:0
      &.on
        bg-image('star24_on')
      &.off
        bg-image('star24_off')
      &.half
        bg-image('star24_half')
  &.star-36
    .star-item
      width:15px
      height:15px
      background-size:15px 15px
      margin-right:6px
      &:last-child
        margin-right:0
      &.on
        bg-image('star36_on')
      &.off
        bg-image('star36_off')
      &.half
        bg-image('star36_half')
  &.star-48
    .star-item
      width:20px
      height:20px
      background-size:20px 20px
      margin-right:22px
      &:last-child
        margin-right:0
      &.on
        bg-image('star48_on')
      &.off
        bg-image('star48_off')
      &.half
        bg-image('star48_half')
</style>